/*
*    l3qd - Light, light, lightweight queue
*    Copyright (C) 2024  Marcus Pedersén marcus@marcux.org
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package show

import (
	"encoding/json"
	"fmt"
	"github.com/spf13/cobra"
	"notabug.org/marcux/l3q/internal/client"
	"notabug.org/marcux/l3q/internal/common"
	"os"
	"strconv"
)

var showJobCmdFlagVerbose, showJobCmdFlagDetail bool

var showJobCmd = &cobra.Command{
	Use:   "job JOBID",
	Args:  cobra.ExactArgs(1),
	Short: "Shows information about specified job.",
	Long: `Description:
  Shows information about specified job.
  JOBID is required as a positional argument and is the id number of job to show.
  To see full information use --details flag.`,
	Run: func(cmd *cobra.Command, args []string) {
		jobid, err := strconv.Atoi(args[0])

		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to parse JOBID: %s, as integer.\nJOBID is required to be a positive integer.\nTry -h or --help for help.\n",
				args[0])

			if showJobCmdFlagVerbose {
				fmt.Fprintf(os.Stderr, "%s\n", err)
			}

			os.Exit(1)
		}

		if jobid <= 0 {
			fmt.Fprintf(os.Stderr, "JOBID is required to be a positive integer.\nTry -h or --help for help.\n")
			os.Exit(1)
		}

		printJob(jobid)
	},
}

func printJob(jobid int) {
	// TODO
	jobs := []common.Job{}
	urlSuffix := fmt.Sprintf("/job?id=%d&tasks", jobid)

	jsonBytes := client.UrlGet(urlSuffix, showJobCmdFlagVerbose)
	err := json.Unmarshal(jsonBytes, &jobs)
	if err != nil {
		if showJobCmdFlagVerbose {
			fmt.Fprintf(os.Stderr, "Failed to decode json string to struct\n%s\n.", err)
		} else {
			fmt.Fprintf(os.Stderr, "Failed to decode json string.\n")
		}
		os.Exit(1)
	}

	if len(jobs) > 1 {
		fmt.Fprintf(os.Stderr, "Wrong response from daemon.\nMore than one job in response from l3qd daemon.")
		os.Exit(1)
	} else if len(jobs) == 0 {
		os.Exit(0)
	}

	j := jobs[0]

	fmt.Printf("%-20s %d\n", "Jobid:", j.Id)
	fmt.Printf("%-20s %s\n", "Name:", j.Name)
	fmt.Printf("%-20s %s\n", "User:", j.User)
	fmt.Printf("%-20s %s\n", "State:", j.State)
	fmt.Printf("%-20s %s\n", "Job type:", j.Type)
	if len(j.Depend) == 0 {
		fmt.Printf("%-20s %s\n", "Depend:", "-")
	} else {
		fmt.Printf("%-20s %s\n", "Depend:", j.Depend)
	}
	fmt.Printf("%-20s %s\n", "Initialize date:", j.InitDate)
	fmt.Printf("%-20s %s\n", "Start date:", j.StartDate)
	fmt.Printf("%-20s %s\n", "End date:", j.EndDate)
	fmt.Printf("%-20s %s\n", "Run time:", j.RunTime)
	fmt.Printf("%-20s %s\n", "Nodes:", j.Nodes)
	fmt.Printf("%-36s %d\n", "Number of nodes:", j.HostsAlloc)
	fmt.Printf("%-36s %d\n", "Number of allocated cores per node:", j.CoresAlloc)
	fmt.Printf("%-36s %d\n", "Number of tasks running:", j.NoTasksRunning)
	fmt.Printf("%-36s %d\n", "Number of tasks terminated:", j.NoTasksFinished)
	fmt.Printf("%-36s %d\n", "Number of error tasks:", j.NoTasksErr)
	fmt.Printf("%-36s %d\n", "Total number of tasks:", len(j.Tasks))
	fmt.Println("")
	fmt.Println("")
	fmt.Println("")
	fmt.Println("Tasks:")

	for _, t := range j.Tasks {
		fmt.Printf("%-20s %d\n", "TaskId:", t.Id)
		fmt.Printf("%-20s %s\n", "Command:", t.Command)
		if showJobCmdFlagDetail {
			fmt.Printf("%-20s %s\n", "Working directory:", t.WorkDir)
		}

		if t.NodeID > 0 {
			fmt.Printf("%-20s %d\n", "Node id:", t.NodeID)
		}

		if len(t.EndTime) == 0 {
			fmt.Printf("%-20s %s\n", "Exit code:", "-")
		} else {
			fmt.Printf("%-20s %d\n", "Exit code:", t.ExitCode)
		}
		fmt.Printf("%-20s %s\n", "Start date:", t.StartTime)

		if showJobCmdFlagDetail {
			fmt.Printf("%-20s %s\n", "End date:", t.EndTime)
			fmt.Printf("%-20s %s\n", "Run time:", t.RunTime)
			fmt.Println("")
			fmt.Println("Output standard out:")
			fmt.Println(t.Stdout)
			fmt.Println("")
			fmt.Println("Output standard error:")
			fmt.Println(t.Stderr)
		}

		fmt.Println("")
	}
}

func init() {
	showJobCmd.Flags().BoolVarP(&showJobCmdFlagVerbose, "verbose", "v", false, "Print verbose output")
	showJobCmd.Flags().BoolVarP(&showJobCmdFlagDetail, "details", "d", false, "Print full detailed information.")
}
